let save_user_role = $('#save_user_roles')
let save_role_permission = $('#save_role_permissions')

function clearAnimation() {
    // 清空用户列表状态
    $('.show_user_status').addClass('d-none').text('Active');
    // 用户列表提示信息隐藏
    $('#user_warining_message').text('').addClass('d-none');
    // 清空角色信息选择
    $('#role_table input').iCheck('uncheck');
    // 角色信息分配设置为普通状态
    $('.set_permission i').removeClass('fa-refresh').removeClass('fa-spin').addClass('fa-paint-brush');
    // 保存角色信息 按钮隐藏
    save_user_role.addClass('d-none');
    // 菜单树取消选择状态
    zTreeObj.checkAllNodes(false);
    // 保存权限信息 按钮隐藏
    save_role_permission.addClass('d-none');
}

function showSelectUser() {
    clearAnimation()
    $(`.user-list #status_${user_key}`).removeClass('d-none');
    if (!user_role.hasOwnProperty(user_key)) {
        $.ajax({
            url: distribute_url,
            async: false,
            data: {"type": "roles", "key": user_key},
            success: function (response) {
                if (response["status"] === 0) {
                    user_role[user_key] = response["data"]["role_list"];
                } else {
                    swal({
                        title: "获取角色信息！",
                        text: "获取角色信息失败，失败原因是: " + response['msg'],
                        icon: "warning",
                        button: " 确 定 ",
                    });
                }
            },
            error: function (response) {
                console.log(response);
            }
        });
    }
    let rlen = user_role[user_key].length
    let no_role_to_pemission = []
    for (let i = 0; i < rlen; i++) {
        $("#role_checkbox_" + user_role[user_key][i]["key"]).iCheck('check');
        if (!role_permission.hasOwnProperty(user_role[user_key][i]["key"])) {
            no_role_to_pemission.push(user_role[user_key][i]["key"])
        }
    }
    if (no_role_to_pemission.length !== 0 && rlen > 0) {
        $.ajax({
            url: distribute_url,
            async: false,
            traditional: true,
            data: {"type": "permissions", "role_list": no_role_to_pemission},
            success: function (response) {
                if (response["status"] === 0) {
                    $.extend(role_permission, response["data"]["menu"]);
                } else {
                    swal({
                        title: "获取权限信息！",
                        text: "获取权限信息失败，失败原因是: " + response['msg'],
                        icon: "warning",
                        button: " 确 定 ",
                    });
                }
            },
            error: function (response) {
                console.log(response);
            }
        });
    }
    zTreeObj.checkAllNodes(false);
    let node, role_key, plen;
    for (let i = 0; i < rlen; i++) {
        role_key = user_role[user_key][i]["key"];
        plen = role_permission[role_key].length
        for (let i = 0; i < plen; i++) {
            node = zTreeObj.getNodeByParam("key", role_permission[role_key][i]["key"], null);
            zTreeObj.checkNode(node, true, true);
        }
    }
    // 禁止 a 标签进行跳转
    return false;
}

// 点击用户 显示当前用户角色和权限信息
$(".ouser").click(function () {
    user_key = $(this).attr("id")
    showSelectUser()
})

// 点击用户状态按钮 转换为可以设置角色
// TODO 没有考虑再点击返回默认状态
$(".show_user_status").click(function () {
    clearAnimation()
    $(this).removeClass('d-none').text('modify')
    save_user_role.attr('user_key', user_key);

    if (!user_role.hasOwnProperty(user_key)) {
        $.ajax({
            url: distribute_url,
            async: false,
            data: {"type": "roles", "key": user_key},
            success: function (response) {
                if (response["status"] === 0) {
                    user_role[user_key] = response["data"]["role_list"];
                } else {
                    swal({
                        title: "获取角色信息！",
                        text: "获取角色信息失败，失败原因是: " + response['msg'],
                        icon: "warning",
                        button: " 确 定 ",
                    });
                }
            },
            error: function (response) {
                console.log(response);
            }
        });
    }
    let rlen = user_role[user_key].length
    for (let i = 0; i < rlen; i++) {
        $("#role_checkbox_" + user_role[user_key][i]["key"]).iCheck('check');
    }
    save_user_role.removeClass('d-none');
    return false;
})

// 点击角色
$('.set_permission').click(function () {
    if ($(this).children('i').hasClass('fa-spin')) {
        clearAnimation()
        showSelectUser()
    } else {
        role_key = $(this).parent().parent().attr('id').split('_')[1]
        clearAnimation()
        $(this).children('i').addClass('fa-refresh').addClass('fa-spin').removeClass('fa-paint-brush');
        save_role_permission.removeClass('d-none');
        $(`#role_checkbox_${role_key}`).iCheck('check');
        if (!role_permission.hasOwnProperty(role_key)) {
            $.ajax({
                url: distribute_url,
                async: false,
                traditional: true,
                data: {"type": "permissions", "role_list": [role_key,]},
                success: function (response) {
                    if (response["status"] === 0) {
                        $.extend(role_permission, response["data"]["menu"]);
                    } else {
                        swal({
                            title: "获取权限信息！",
                            text: "获取权限信息失败，失败原因是: " + response['msg'],
                            icon: "warning",
                            button: " 确 定 ",
                        });
                        return false;
                    }
                },
                error: function (response) {
                    console.log(response);
                    return false;
                }
            });
        }
        if (role_permission.hasOwnProperty(role_key)) {
            let plen = role_permission[role_key].length
            for (let i = 0; i < plen; i++) {
                node = zTreeObj.getNodeByParam("key", role_permission[role_key][i]["key"], null);
                zTreeObj.checkNode(node, true, true);
            }
        } else {
            swal({
                title: "权限信息没有获取到！",
                text: "权限信息没有获取到对应的权限信息",
                icon: "info",
                button: " 确 定 ",
            });
        }
    }

    return false;
});

// 提交用户角色信息
save_user_role.click(function () {
    let rl = [];
    $('input:checkbox:checked').each(function (index, item) {
        rl.push($(this).val());
    });
    $.ajax({
        data: {'user_key': user_key, 'role_list': rl, 'type': 'set_roles', 'csrfmiddlewaretoken': token},
        type: 'POST',
        url: distribute_url,
        traditional: true,
        success: function (data) {
            if (data['status'] === 0) {
                toastr["success"]("保存成功", data['msg']);
                user_role[user_key] = []
                let rlen = rl.length
                for (let i = 0; i < rlen; i++) {
                    user_role[user_key].push({"key": rl[i]})
                }
                showSelectUser()
            } else {
                toastr["error"]("保存出错", data['msg'])
            }
        },
    })
})

// 提交角色权限信息
save_role_permission.click(function () {
    let pl = [];
    nodes = zTreeObj.getCheckedNodes(true);
    let i;
    for (i = 0; i < nodes.length; i++) {
        // 如果选择节点有permission属性，并且pl数组中没有当前权限，则把当前权限加入列表
        // 菜单节点permission属性是菜单关联权限的key值
        if (nodes[i].permission && pl.indexOf(nodes[i].permission) === -1) {
            pl.push(nodes[i].permission);
        }
    }
    $.ajax({
        data: {'role_key': role_key, 'permission_list': pl, 'type': 'set_permission', 'csrfmiddlewaretoken': token},
        type: 'POST',
        url: distribute_url,
        traditional: true,
        success: function (data) {
            if (data['status'] === 0) {
                toastr["success"]("保存成功", data['msg']);
                role_permission[role_key] = []
                let rlen = nodes.length
                let rpitem;
                for (i = 0; i < rlen; i++) {
                    rpitem = {"key": nodes[i].key, "permission": nodes[i].permission}
                    if (nodes[i].permission && role_permission[role_key].indexOf(rpitem) === -1) {
                        role_permission[role_key].push(rpitem)
                    }
                }
            } else {
                toastr["error"]("保存出错", data['msg'])
            }
        },
    })
})

function permissionTreeInit() {
    // 菜单树初始化初始化参数
    let setting = {
        check: {
            enable: true
        },
        view: {
            fontCss: {'color': 'black', 'font-weight': 'bold'},//字体样式函数
            showLine: false,
        },
        data: {
            simpleData: {
                enable: true,
            }
        },
    };
    $.ajax({
        url: distribute_url,
        async: false,
        data: {"type": "menu_ztree"},
        success: function (response) {
            // 菜单树节点信息请求成功
            if (response.status === 0 && response.hasOwnProperty("data")) {
                let nodes = response["data"]["menu_tree"]
                // 处理数据,符合初始化信息
                for (let count = 0, len = nodes.length; count < len; count++) {
                    nodes[count]["id"] = nodes[count]["key"]
                    nodes[count]["pId"] = nodes[count]["parent"]
                }
                // 初始化权限树
                zTreeObj = $.fn.zTree.init($("#PermissionTree"), setting, nodes);
            } else {
                // 菜单树请求失败 提示失败信息
                swal({
                    title: "权限树创建失败！",
                    text: "权限树创建失败，失败原因是: " + response['msg'],
                    icon: "warning",
                    button: " 确 定 ",
                });
            }
        },
        error: function (response) {
            console.log(response);
        }
    });
}

// 页面初始化操作
$(document).ready(function () {
    // checkbox样式
    $('#role_table input').iCheck({
        checkboxClass: 'icheckbox_square-blue',
        radioClass: 'iradio_square-blue',
    });
    // 初始化权限树
    permissionTreeInit();
    // 初始化toastr
    toastr.options = {
        "closeButton": true,
        "debug": false,
        "progressBar": true,
        "preventDuplicates": false,
        "positionClass": "toast-top-right",
        "onclick": null,
        "showDuration": "400",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };
})
